package com.libra.service.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.hibernate.validator.HibernateValidator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.libra.service.exception.BussinessExection;

public class ValidationUtils {
//	public static void validationVo(BindingResult bindingResult) throws BussinessExection{
//		if(bindingResult.hasErrors()){
//			FieldError fieldError = bindingResult.getFieldError();
//			String fieldMsg = fieldError.getDefaultMessage();
//			int num = fieldMsg.indexOf(":");
//			if(-1 == num){
//				throw new BussinessExection(fieldError.getCode(),fieldMsg);
//			}
//            throw new BussinessExection(fieldMsg.substring(0,num),fieldMsg.substring(num+1,fieldMsg.length()));
//        }
//	}
	//校验方法二
	private static Validator validator = Validation
			.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

	public static <T> String validate(T obj) throws BussinessExection {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
		// 抛出检验异常
		if (constraintViolations.size() > 0) {
			String msg = constraintViolations.iterator().next().getMessage();
			System.out.println("msg:"+msg);
			return msg;
//			int num = msg.indexOf(":");
//			if(-1 == num){
//				throw new BussinessExection("9998",msg);
//			}
//			throw new BussinessExection(msg.substring(0,num),msg.substring(num+1,msg.length()));
		}
		return null;
	}
}
